import util from '@/libs/util';
import getDate from '../../util/getDate';
import tinymce from 'tinymce';
import Cookies from 'js-cookie';
import * as orderList from './orderList.js';

export default {
    name: 'exportable-table',
    data() {
        return {
            columns: [
                {
                    title: '活动（培训）名称', key: 'activityId', render: (h, params) => {
                    return h('div', {}, params.row.activity.name)
                }
                },
                {
                    title: '会员名称', key: 'userId', render: (h, params) => {
                    return h('div', {}, params.row.user.name)
                }
                },
                {title: '订单金额', key: 'moneysum'},
                {title: '订单数量', key: 'ordersnums'},
                {
                    title: '创建时间', key: 'createtime', render: (h, params) => {
                    return h('div', {}, getDate.getDate(params.row.createtime, 'date'))
                }
                },
                {
                    title: '付款时间', key: 'paytime', render: (h, params) => {
                    return h('div', {}, getDate.getDate(params.row.paytime, 'date'))
                }
                },
                {
                    title: '订单状态', key: 'status', width: 85,
                    render: (h, params) => {
                        let texts = '';
                        if (params.row.status == '10') {
                            texts = "待付款"
                        } else if (params.row.status == '11') {
                            texts = "已付款"
                        } else if (params.row.status == '12') {
                            texts = "待出发"
                        } else if (params.row.status == '13') {
                            texts = "待评价"
                        } else if (params.row.status == '14') {
                            texts = "已评价"
                        } else if (params.row.status == '20') {
                            texts = "不需审核"
                        } else if (params.row.status == '21') {
                            texts = "待审核"
                        } else if (params.row.status == '22') {
                            texts = "已审核"
                        }
                        return h('div', {}, texts)
                    }
                },
                {
                    title: '操作', key: 'action', width: 200, align: 'center',
                    render: (h, params) => {
                        let assBoo = 'none';
                        let audBoo = 'none';
                        if (params.row.status === '13') {
                            assBoo = 'inline';
                        }else if (params.row.status === '21') {
                            audBoo = 'inline';
                        }
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px',
                                    display: audBoo
                                },
                                on: {
                                    click: () => {
                                        this.audit(params.row);
                                    }
                                }
                            }, '审核'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.history(params.row);
                                    }
                                }
                            }, '查看历史'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.detail(params.row);
                                    }
                                }
                            }, '详情'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px',
                                    display: assBoo
                                },
                                on: {
                                    click: () => {
                                        this.setAss(params.row);
                                    }
                                }
                            }, '评价')
                        ]);
                    }
                }
            ],
            historyColumns: orderList.historyColumns,
            data: [],
            historyData: [],
            formData: {},
            formAssess: {},
            query: {
                activityName: '',
                isdiscount: '',
                status: '',
                bs: ''
            },
            viewModalVisible: false,
            assModalVisible: false,
            hisModalVisible: false,
            pageIndex: 1,
            pageSize: 10,
            total: 0,

            hisIndex: 1,
            hisSize: 5,
            hisTotal: 0,
            hisUserId: '',

            prices: [],
            contacts: [],
            ratio: ''
        };
    },
    mounted() {
        this.loadList();
    },
    methods: {
        loadList() {
            let baseuser = eval('(' + Cookies.get('baseUser') + ')')
            util.ajax.post('/busine/orders/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                activityName: this.query.activityName,
                isdiscount: this.query.isdiscount,
                status: this.query.status,
                userId: baseuser.id,
                orgId: baseuser.orgId,
                bs: this.query.bs
            })).then(res => {
                this.data = res.data.data.pageInfo.list;
                this.total = res.data.data.pageInfo.total;
                let menCount = res.data.data.menCount.length
                let womenCount = res.data.data.womenCount.length
                let commonNum = 1;
                if (menCount > 0 && womenCount > 0){
                    commonNum = this.common(menCount, womenCount);
                }
                this.ratio = ((menCount/commonNum) + ':' + (womenCount/commonNum));
            });
        },
        refresh() {
            this.query = {
                activityName: '',
                isdiscount: '',
                status: '',
                bs: ''
            };
            this.pageIndex = 1
            this.loadList();
        },
        detail(obj) {
            let formData = {};
            for (let key in obj) {
                formData[key] = obj[key];
            }
            formData.createtime = getDate.getDate(formData.createtime, 'time');
            formData.departtime = getDate.getDate(formData.departtime, 'date');
            formData.paytime = getDate.getDate(formData.paytime, 'time');
            formData.activityName = formData.activity.name;
            formData.userName = formData.user.name;
            let texts = '';
            if (formData.status == '10') {
                texts = "待付款"
            } else if (formData.status == '11') {
                texts = "已付款"
            } else if (formData.status == '12') {
                texts = "待出发"
            } else if (formData.status == '13') {
                texts = "待评价"
            } else if (formData.status == '14') {
                texts = "已评价"
            }else if (formData.status == '20') {
                texts = "不需审核"
            }else if (formData.status == '21') {
                texts = "待审核"
            }else if (formData.status == '22') {
                texts = "已审核"
            }
            formData.type = texts;

            this.formData = formData;
            util.ajax.post('/busine/orders/detail', util.toFormData(formData)).then(res => {
                this.formAssess = res.data.data.assess;
                this.prices = res.data.data.prices;
                this.contacts = res.data.data.contacts;
                this.viewModalVisible = true;
            });
        },
        init(id) {
            let _this = this;
            this.$nextTick(() => {
                let vm = this;
                let height = document.body.offsetHeight - 500;
                tinymce.init({
                    selector: ('#' + id),
                    branding: false,
                    elementpath: false,
                    height: height,
                    language: 'zh_CN.GB2312',
                    menubar: 'edit insert view format table tools',
                    plugins: [
                        'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                        'searchreplace visualblocks visualchars code fullpage',
                        'insertdatetime media nonbreaking save table contextmenu directionality',
                        'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                    ],
                    toolbar1: ' newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                    autosave_interval: '20s',
                    image_advtab: true,
                    table_default_styles: {
                        width: '100%',
                        borderCollapse: 'collapse'
                    },
                    setup: function (editor) {
                        editor.on('init', function (e) {
                            if (_this.formData[id]) {
                                tinymce.get(id).setContent(_this.formData[id]);
                            }
                        });
                        editor.on('change', function (e) {
                            _this.formData[id] = tinymce.get(id).getContent();
                        });
                    }
                });
            });
        },
        setAss(obj) {
            this.formData = {};
            this.formData.orderId = obj.id;
            this.assModalVisible = true;
            this.init('comment');
        },
        assSave() {
            let formData = this.formData;
            if (!formData.level) {
                this.$Message.error('请给活动评分！');
                return;
            }
            util.ajax.post('/busine/orders/saveAssess', util.toFormData(formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.assCancel();
                    this.$Message.success('评价成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        assCancel() {
            this.assModalVisible = false;
            tinymce.get('comment').destroy();
        },
        history(obj){
            let userId;
            if(obj.user){
                userId = this.hisUserId = obj.user.id;
            }else{
                userId = this.hisUserId
            }
            util.ajax.post('/busine/orders/listByUser', util.toFormData({
                page: this.hisIndex,
                size: this.hisSize,
                userId: userId
            })).then(res => {
                this.historyData = res.data.data.list;
                this.hisTotal = res.data.data.total;
                this.hisModalVisible = true;
            });
        },
        hisClose() {
            this.hisModalVisible = false;
        },
        audit(obj) {
            let userId = obj.user.id;
            util.ajax.post('/busine/orders/listByUser', util.toFormData({
                page: 1,
                size: 10,
                userId: userId
            })).then(res => {
                let historyList = this.historyData = res.data.data.list;
                let signBoo = true;
                for (let i=0 ; i < historyList.length ; i++) {
                    if(historyList[i].signstate == 0){
                        signBoo = false;
                    }
                }
                if (!signBoo) {
                    this.$Modal.confirm({
                        title: '警告',
                        content: '该用户有不良记录是否继续审核？',
                        okText: '继续',
                        cancelText: '查看历史',
                        onOk: () => {
                            util.ajax.post('/busine/orders/audit', util.toFormData({
                                id: obj.id
                            })).then(res => {
                                this.$Message.success('审核完成！');
                                this.loadList();
                            })
                        },
                        onCancel: () => {
                            this.hisModalVisible = true;
                        }
                    });
                }
            });
        },
        common(m, n) {
            while (n != 0) {
                var r = m % n;
                m = n;
                n = r;
            }
            return m;
        }
    }
};